//
//  YBBLEAdvertisementData.m
//  youonBikePlanA
//
//  Created by LPC on 2017/11/22.
//  Copyright © 2017年 audi. All rights reserved.
//

#import "YBBLEAdvertisementData.h"

@implementation YBBLEAdvertisementData

- (void)parsing{
    NSString *temp16 = [NSString stringWithFormat:@"%@",_kCBAdvDataManufacturerData];
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"\\<\\>"];
    temp16 = [temp16 stringByTrimmingCharactersInSet:set];
    temp16 = [temp16 stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (temp16.length < 8) {
        NSLog(@"解析蓝牙锁报文错误");
        return;
    }
    NSString *version16 = [temp16 substringWithRange:NSMakeRange(4, 4)];
    _yb_version10 = [NSString stringWithFormat:@"%lu",strtoul([version16 UTF8String],0,16)];
    _yb_version16 = version16;
    if (!self.autoReturn) {
        NSLog(@"不支持自动还车");
        return;
    }
    
    if (temp16.length < 14) {
        NSLog(@"解析蓝牙锁报文错误");
        return;
    }
    
    NSString *LockPowerinfo16Str = [temp16 substringWithRange:NSMakeRange(10, 2)];
    NSString *LockWDinfo16Str =  [temp16 substringWithRange:NSMakeRange(12, 2)];
    _yb_power = [NSString stringWithFormat:@"%0.1f",strtoul([LockPowerinfo16Str UTF8String],0,16) *0.1];;
    _yb_temperature = [NSString stringWithFormat:@"%lu",strtoul([LockWDinfo16Str UTF8String],0,16)];
    _yb_state = [temp16 substringWithRange:NSMakeRange(8, 2)];
    NSLog(@"==锁状态=%@",_yb_state);
    _report = [NSString stringWithFormat:@"%@,%@,%@,%@",self.formatState == BLE_Open?@"OPEN":@"CLOSE",_yb_power,_yb_temperature,_yb_version10];
}

- (BOOL)autoReturn{
    if (!_yb_version10|| _yb_version10.length == 0) {
        return NO;
    }
    _autoReturn = _yb_version10.integerValue>=17?YES:NO;
    return _autoReturn;
}

/**
 *  55 ->普通开锁状态
 *  66 ->有桩开成锁不上
 *  77 ->无桩开成锁不上
 *  88 ->中途开锁状态
 *  AA ->普通关锁状态
 *  BB ->区域关锁状态
 *  CC ->定点关锁状态
 *  DD ->中途关锁状态
 */

- (BLEState)formatState{
    if([_yb_state isEqualToString:@"aa"] || [_yb_state isEqualToString:@"bb"] || [_yb_state isEqualToString:@"cc"]) {
        return BLE_Close;
    }else if ([_yb_state isEqualToString:@"dd"]){//临时锁车
        return BLE_snapClose;
    }
    return BLE_Open;
}

@end
